#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2017/7/31 17:52
@Author  : tonychao
@File    : trainModelFromDB.py
命令格式，使用 DaemonForAnswer.py app_md5
"""

def OutPut(line):
    print ("[python 应用时间预测模型]:\t"+line)
    sys.stdout.flush()

#当前脚本目录
import sys,os
#print os.path.split( os.path.realpath( sys.argv[0] ) )
ScriptPath = os.path.split( os.path.realpath( sys.argv[0] ) )[0]
ScriptPath=ScriptPath+'/'
OutPut("当前脚本目录："+ScriptPath)

import time

import DBReader
import numpy as np

#获得数据
app_md5=sys.argv[1]
className=sys.argv[2]
inputConf1,inputConf2,inputConf3,runTime1,runTime2,runTime3,totalRunTime= DBReader.readDB(app_md5,className)


# 数据标准化 Standardize features by removing the mean and scaling to unit variance
from sklearn.preprocessing import StandardScaler
X_scaler= StandardScaler();Yscaler = StandardScaler()
inputConf1 = X_scaler.fit_transform(inputConf1);
runTime1=np.array(runTime1);
runTime1=runTime1.reshape(-1,1);
runTime1=X_scaler.fit_transform(runTime1);

inputConf2 = X_scaler.fit_transform(inputConf2);
runTime2=np.array(runTime2);
runTime2=runTime2.reshape(-1,1);
runTime2=X_scaler.fit_transform(runTime2)

inputConf3 = X_scaler.fit_transform(inputConf3);
runTime3=np.array(runTime3);
runTime3=runTime3.reshape(-1,1);
runTime3=X_scaler.fit_transform(runTime3);

starttime = time.time()

#在这里需要说明的是运行时间在时间的问题，是否需要标准化？

OutPut("choose and select model")
from ModelSelection import chooseBestModel
from ModelSelection import modelTest_LeaveOneOut
from MLModels import getModelList

# model 1,2,3
a= inputConf1[0]
model1=chooseBestModel(inputConf1,runTime1,getModelList(),modelTest_LeaveOneOut); model1.fit(inputConf1,runTime1) #每一次必须重开一个list
model2=chooseBestModel(inputConf2,runTime2,getModelList(),modelTest_LeaveOneOut); model2.fit(inputConf2,runTime2)
model3=chooseBestModel(inputConf3,runTime3,getModelList(),modelTest_LeaveOneOut); model3.fit(inputConf3,runTime3)


#存贮模型列表
from sklearn.externals import joblib  # save the model in a file
def saveModelsToFiles(saveModelPath,ModelList):
    for i in range(0,len(ModelList)):
        joblib.dump(ModelList[i], saveModelPath+'stageModel_%d.pkl'%(i))


OutPut("saveing modle")
modelPath=ScriptPath + 'savedModels/'+app_md5+"_"+className+"/"
if not os.path.exists(modelPath):
     os.makedirs(modelPath)
saveModelsToFiles(modelPath,[model1,model2,model3])


sys.stdout.flush()
exit(0)